import configparser
import io
import psycopg2
from src import SysConfig

sys_config = SysConfig.sys_config
class ReadMapServiceConfig:
    def __init__(self):
        self.cp = configparser.ConfigParser()
        self.servicesConfigs = {}

        # 从文件获取服务配置列表
        if sys_config['startType'] == 'file':
            self.configPath = sys_config['servicesListPath']
            self.configPath = self.configPath.replace('\\', '/')
            with io.open(self.configPath, 'r', encoding='utf8') as f:
                self.cp.read_file(f)

            sections = self.cp.sections()

            for i in sections:
                self.servicesConfigs[i] = self.cp.get(i, 'config_path')
        # 从数据库获取服务配置列表
        elif sys_config['startType'] == 'db':
            dbConfig = sys_config['DBConnectInfo']

            conn = ''
            try:
                conn = psycopg2.connect(database=dbConfig['database'], user=dbConfig['user'], password=dbConfig['password'],
                                        host=dbConfig['host'], port=dbConfig['port'])

            except Exception as e:
                print(e)
                print('连接数据库时出错')

            cur = ''
            try:
                cur = conn.cursor()
                cur.execute("select tilemap.svr_get_services('{}', '{""}')")
                result = cur.fetchall()
                result = result[0][0]
                for i in result:
                    if i['enable'] is True:
                        self.servicesConfigs[i['name']] = i['config_path']
            except Exception as e:
                print(e)
                print('执行数据库查询时出错')
            finally:
                cur.close()
                conn.close()

    # 返回对应服务数据的地址
    def getParameter(self, servicename):
        return self.servicesConfigs[servicename]

    # 返回所有的key(具体数据名称)
    def getAll(self):
        return self.servicesConfigs.keys()
